const Router = require('@koa/router')
const router = new Router()
const { verify } = require('../utils/jwt.js')
const { findNoteListByType, findNoteById, saveNote } = require('../controllers/index.js')
const jwt = require('jsonwebtoken')
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');

router.get('/findNoteListByType', verify(), async (ctx) => {

    const { type } = ctx.request.query   // 从url 后解析参数
    // console.log(type);

    try {
        const token = ctx.header.authorization
        const decoded = jwt.verify(token, '晓慧')
        let UseId = decoded.id;
        // console.log(UseId);
        const res = await findNoteListByType(UseId, type);
        // console.log(res);

        if (res.length > 0) {
            res.status = 200
            ctx.body = {
                code: '1',
                msg: '查询成功',
                data: res
            }
        } else {
            ctx.body = {
                code: '0',
                msg: '暂无数据',
                data: []
            }
        }
    } catch (err) {
        console.log('查询失败', err);
        ctx.body = {
            code: '0',
            msg: '查询失败',
            data: []
        }
    }

})

router.get('/findNoteById', verify(), async (ctx) => {
    const { id } = ctx.request.query
    try {
        const res = await findNoteById(id)
        console.log(res)
        if (res) {
            ctx.body = {
                code: '1',
                msg: '查询成功',
                data: res
            }
        } else {
            ctx.body = {
                code: '0',
                msg: '查询失败',
            }
        }
    } catch (err) {
        console.log('查询失败', err);
        ctx.body = {
            code: '0',
            msg: '查询失败',
        }
    }
})

router.post('/saveNote', verify(), async (ctx) => {
    try {
        const token = ctx.header.authorization
        const decoded = jwt.verify(token, '晓慧')
        let UseId = decoded.id;
        let author = decoded.username;
        let { title, content, images, type, create_time } = ctx.request.body

        // 处理图片保存
        const imageUrls = [];
        if (images && Array.isArray(images)) {
            for (const image of images) {
                // 检查是否有base64数据
                if (image.base64) {
                    // 提取base64数据
                    const base64Data = image.base64.replace(/^data:image\/\w+;base64,/, '');
                    const buffer = Buffer.from(base64Data, 'base64');
                    // 生成唯一文件名
                    const fileName = `${uuidv4()}.png`;
                    const filePath = path.join(__dirname, '..', 'public', 'uploadImages', fileName);
                    // 保存图片
                    fs.writeFileSync(filePath, buffer);
                    // 生成可访问的URL
                    const imageUrl = `http://localhost:3000/uploadImages/${fileName}`;
                    imageUrls.push({ url: imageUrl });
                }
            }
        }

        const res = await saveNote({
            userId: UseId,
            author,
            title,
            content,
            images: imageUrls,
            type,
            create_time
        })

        console.log(res);
        if (res) {
            ctx.body = {
                code: '1',
                msg: '保存成功',
            }
        }
    } catch (err) {
        console.log('保存失败', err);
        ctx.body = {
            code: '0',
            msg: '保存失败,捕捉到错误',
        }
    }
})

module.exports = router